package com.Work;

import com.alibaba.fastjson2.JSON;
import lombok.*;

import java.io.*;

public class Exam01_a {
    public static void main(String[] args) {
        // 分别使用JSON和序列化反序列化实现
        File file = new File("days9.15/src/txtpack/1.txt");
        File file2 = new File("days9.15/src/txtpack/2.txt");
        exam2(file2);
    }

    private static void exam1(File file) {
        try {
            // 序列化对象到文件
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(file));
            Person per = new Person("张三", "不知道什么玩意", null);
            Person per1 = new Person("李四", "我也不知道", per);
            objectOutputStream.writeObject(per1);
            objectOutputStream.close();

            // 从文件中反序列化对象
            ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(file));
            Person o = (Person) objectInputStream.readObject();
            objectInputStream.close();

            System.out.println(o);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static void exam2(File file) {
        try (FileWriter writer =new FileWriter(file);
             FileReader reader = new FileReader(file)
        ) {
            Person per = new Person("张三", "不知道什么玩意", null);
            Person per1 = new Person("李四", "我也不知道", per);
            String json = JSON.toJSONString(per1);
            writer.write(json);
            writer.flush();
            char[] chars = new char[200];
            int size;
            while ((size = reader.read()) != -1) {
                reader.read(chars,0,size);
            }
            System.out.println(chars);
        }catch (IOException e){
            System.out.println(e.getMessage());
        }
    }
}

@Data
@AllArgsConstructor
@NoArgsConstructor
class Person implements Serializable {

    private String name;
    private String no;
    private Person son;

    @Override
    public Object clone() {
        Person clone = new Person();
        if (name == null || no == null || son == null) {
            return null;
        }
        clone.setName(name);
        clone.setNo(no);
        clone.setSon(son);
        return clone;
    }
}
